package com.example.jpetstoreclient.controller;

import com.example.jpetstoreclient.common.CommonResponse;
import com.example.jpetstoreclient.domain.User;
import com.example.jpetstoreclient.service.UserService;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Validated
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    //  登录
    @PostMapping("/login")
    public CommonResponse<User> login(@RequestParam("username") @NotBlank(message = "用户名不能为空") String username,
                                      @RequestParam("password") @NotBlank(message = "密码不能为空") String password){
        return userService.login(username, password);
    }

    //  查询有无重名用户
    @GetMapping("/find/name/{username}")
    public CommonResponse<User> detectSameUsername(@PathVariable("username") @NotBlank(message = "查询的用户名不能为空") String username){
        if (userService.checkUsername(username)) return CommonResponse.createForError("用户存在");
        return CommonResponse.createForSuccessMessage("用户不存在");
    }

    //  查询有无相同邮箱
    @GetMapping("/find/email/{email}")
    public CommonResponse<User> detectSameEmail(@PathVariable("email") @NotBlank(message = "查询的邮箱不能为空") String email){
        if (userService.checkEmail(email)) return CommonResponse.createForError("邮箱存在");
        return CommonResponse.createForSuccessMessage("邮箱不存在");
    }

    //  查询有无相同手机
    @GetMapping("/find/phone/{phone}")
    public CommonResponse<User> detectSamePhone(@PathVariable("phone") @NotBlank(message = "查询的手机号不能为空") String phone){
        if (userService.checkPhone(phone)) return CommonResponse.createForError("手机存在");
        return CommonResponse.createForSuccessMessage("手机不存在");
    }

    @PutMapping("/update")
    public CommonResponse<User> updateUser(@RequestBody User user){
        return userService.updateUser(user);
    }

    @PostMapping("/regist")
    public CommonResponse<User> regist(@RequestBody User user){
        return userService.register(user);
    }

    @GetMapping("/verify")
    public CommonResponse<User> verify(@RequestParam("id") @NotNull(message = "用户ID不能为空") int id,
                                       @RequestParam("password") @NotBlank(message = "密码不能为空") String password){
        if (userService.verifyPassword(id, password)) return CommonResponse.createForSuccessMessage("密码正确");
        return CommonResponse.createForError("密码错误");
    }
}
